/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.math
{
	import com.qb9.flashlib.lang.fold;
	
	/** Math-related utility functions */
	public class QMath
	{
		/**
		 * Convert from degrees to radians.
		 */
		public static function deg2rad(deg:Number):Number
		{
			return Math.PI * deg / 180;
		}
		
		/**
		 * Convert from radians to degrees.
		 */
		public static function rad2deg(rad:Number):Number
		{
			return 180 * rad / Math.PI;
		}

		/**
		 * Clamp: ensure that <code>min &lt;= input &lt;= max</code>.
		 *
		 * <p>Usage example:
		 * <pre>
		 * var angle:Number = 390;
		 * var clampedAngle:Number = clamp(angle, 0, 360);
		 * trace(clampedAngle); // prints 360
		 * </pre>
		 * </p>
		 */
		static public function clamp(input:Number, min:Number, max:Number):Number 
		{
        	return (input < min) ? min : (input > max) ? max : input;
    	}
		
		/**
		 * Clamp with rotation: ensure that <code>min &lt;= input &lt;= max</code>.
		 *
		 * <p>Usage example:
		 * <pre>
		 * var angle:Number = 390;
		 * var clampedAngle:Number = clamprot(angle, 0, 360);
		 * trace(clampedAngle); // prints 30
		 * </pre>
		 * </p>
		 */
		static public function clamprot(input:Number, min:Number, max:Number):Number
		{
			var diff:Number = max - min;
			while (input < min)
				input += diff;
			while (input > max)
				input -= diff;
			return input;
		}
		
		/**
		 * Return the sum of all its members
		 */
		static public function sum(arr:Array) : Number
		{
			return fold(arr, Operator.add, 0) as Number;
		}
		
		/**
		 * Return the sign of a number (-1, 0, 1).
		 */
		static public function sign(num:Number) : int
		{
			return num > 0 ? 1 : num < 0 ? -1 : 0
		}
	}
}

